package com.itcpeng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itcpeng.constant.MessageConstant;
import com.itcpeng.entity.PageResult;
import com.itcpeng.entity.QueryPageBean;
import com.itcpeng.entity.Result;
import com.itcpeng.pojo.Permission;
import com.itcpeng.service.PermissionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Reference
    private PermissionService permissionService;


  //获得分页数据对象
    @RequestMapping("/findPage")
    @PreAuthorize("hasAuthority('CHECKITEM_QUERY')")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        //调用业务获得分页数据对象
        PageResult pageResult = permissionService.findPage(queryPageBean);
        return pageResult;
    }


  //添加权限
    @RequestMapping("/add")
    public Result add(@RequestBody Permission permission) {
        try {
            permissionService.add(permission);
            return new Result(true, MessageConstant.ADD_Permission_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_Permission_FAIL);
        }
    }



   //根据id删除权限
    @GetMapping(value = "/delete")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result delete(Integer id) {
        try {
            permissionService.delete(id);
            return new Result(true, MessageConstant.DELETE_Permission_SUCCESS);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_Permission_FAIL);
        }
    }


    //根据id查询检查项
    @GetMapping(value = "/findById")
    public Result findById(Integer id) {
        try {
            //调用业务
            Permission permission = permissionService.findById(id);
            return new Result(true, MessageConstant.QUERY_Permission_SUCCESS, permission);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_Permission_FAIL);
        }
    }


    //编辑检查项
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result edit(@RequestBody Permission permission) {
        try {
            //调用业务，编辑检查项
            permissionService.edit(permission);
            return new Result(true, MessageConstant.EDIT_Permission_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_Permission_FAIL);
        }
    }

}
